<template>
    <div ref="ChartWithLine" class="public-charts-with-line"></div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import * as echarts from "echarts";
import { Resize } from "@/utils";

const props = withDefaults(
    defineProps<{
        options: echarts.EChartsCoreOption;
    }>(),
    {}
);

let chartLine = null; // 图表实例
let isInitChart = false; // 是否初始化图表设置
const ChartWithLine = ref(null); // dom实例
const resize = new Resize();

watch(
    () => props.options,
    () => {
        chartLine.hideLoading();
        if (!isInitChart) {
            initEcharts();
        }
        chartLine.setOption(props.options);
    }
);

onMounted(() => {
    chartLine = echarts.init(ChartWithLine.value);
    chartLine.showLoading({
        text: "loading",
        color: "#fff",
        textColor: "#fff",
        maskColor: "rgba(255, 255, 255, 0)",
        zlevel: 0,
    });

    resize.on(chartLine.resize);

    if (Object.keys(props.options).length) {
        initEcharts();
        chartLine.setOption(props.options);
    }
});

const initEcharts = () => {
    isInitChart = true;
    chartLine.hideLoading();
    chartLine.setOption(props.options);
};

onBeforeUnmount(() => {
    if (!chartLine) return;
    resize.remove(chartLine.resize);
    chartLine.dispose();
    chartLine = null;
});
</script>

<style lang="scss" scoped>
.public-charts-with-line {
    width: 100%;
    z-index: 10;
    height: 100%;
}
</style>
